<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px">
      <el-form-item label="版本" prop="version">
        <el-select v-model="queryParams.version" class="!w-240px" clearable placeholder="请选择版本">
          <el-option v-for="version in versionList" :key="version.id" :label="version.versionName"
            :value="version.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="author">
        <el-input v-model="queryParams.author" class="!w-240px" clearable placeholder="请输入创建人"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" end-placeholder="结束日期"
          start-placeholder="开始日期" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="openForm('create')" v-if="editePermission">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column align="center" label="序号" type="index" width="80" />
      <!-- <el-table-column align="center" label="项目名称" prop="name" /> -->
      <el-table-column align="center" label="版本" prop="version" />
      <el-table-column align="center" label="任务简述" prop="description" />
      <el-table-column align="center" label="轮次" prop="rounds">
        <template #default="scope">
          <div v-if="scope.row.rounds === 0">未产生</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="需求数量" prop="demandsCount" />
      <el-table-column align="center" label="创建人" prop="author" />
      <el-table-column :formatter="dateFormatter" align="center" label="更新时间" prop="updateDate" width="180" />
      <el-table-column align="center" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TEST_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :width="300" align="center" label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)"
            v-if="(scope.row.status === 1 || scope.row.status === 4) && editePermission">
            编辑
          </el-button>
          <el-button link type="primary" @click="openForm('view', scope.row.id)"
            v-if="scope.row.status !== 1 || viewPermission">
            查看
          </el-button>
          <el-button link type="primary" @click="handleSubmit(scope.row.id)"
            v-if="scope.row.status === 1 && editePermission">
            提交
          </el-button>
          <el-button link type="primary" @click="handleExamine(scope.row.id)"
            v-if="scope.row.status === 2 && examinePermission">
            审批
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"
            v-if="(scope.row.status === 1 || scope.row.status === 2 || scope.row.status === 4) && editePermission">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TestForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TestApi from '@/api/test'
import TestForm from './TestForm.vue'
import { dateFormatter } from '@/utils/formatTime'
import { ElMessageBox } from 'element-plus'

defineOptions({ name: 'TestingManage' })

import { useAppStore } from '@/store/modules/app'
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const appStore = useAppStore()
let projectId = computed(() => appStore.getSelectProject)
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  version: null,
  author: null,
  createTime: '',
  projectId: projectId.value,
  pageNo: 1,
  pageSize: 10,
})
const queryFormRef = ref() // 搜索的表单

watch(projectId, (newValue) => {
  queryParams.projectId = newValue
  getList()
  getversionList()
  getProjectMemberRole()
})

/** 查询提测列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TestApi.getPage(queryParams)
    data.records.forEach(item => {
      item.name = item.projectId.name;
      item.author = item.author.nickname;
      item.version = item.version.versionName
    });
    list.value = data.records
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const role = ref('')
const editePermission = computed(() => ['admin', 'projectManager', 'developer'].includes(role.value))
// const deletePermission = computed(() => ['admin', 'projectManager'].includes(role.value))
const viewPermission = computed(() => ['admin', 'projectManager', 'developer', 'testManager', 'tester'].includes(role.value))
const examinePermission = computed(() => ['admin', 'testManager'].includes(role.value))

// 获取人员在项目中角色
const getProjectMemberRole = async () => {
  let data = await TestApi.getProjectMemberRole({ projectId: projectId.value })
  role.value = data
}

const versionList = ref([])
/** 获取版本列表 */
const getversionList = async () => {
  const data = await TestApi.getVersion({ projectId: projectId.value })
  versionList.value = data
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, projectId)
}

/** 提交按钮操作 */
const handleSubmit = async (id: number) => {
  try {
    // 提交的二次确认
    await message.confirm('是否提交本次提测清单？')
    // 发起提交
    await TestApi.submitStatus({
      id: id,
      status: 2
    })
    message.success('提交成功')
    // 刷新列表
    await getList()
  } catch {
    message.info('取消提交')
  }
}

/** 审批按钮操作 */
const handleExamine = async (id: number) => {
  ElMessageBox.confirm(
    '是否确认通过本次提测清单？',
    '审批确认通知',
    {
      distinguishCancelAndClose: true,
      confirmButtonText: '通过',
      cancelButtonText: '不通过',
    }
  )
    .then(async () => {
      await TestApi.approveStatus({
        id: id,
        status: 3
      })
      message.success('审批通过')
      // 刷新列表
      await getList()
    })
    .catch(async (action) => {
      if (action === 'cancel') {
        await TestApi.approveStatus({
          id: id,
          status: 4
        })
        message.info('审批不通过')
      } else {
        message.info('取消审批')
      }
      await getList()
    })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TestApi.deleteTesting(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 初始化 **/
onMounted(() => {
  if (projectId.value) {
    getList()
    getversionList()
    getProjectMemberRole()
  }
})
</script>
